package com.lagou.controller;

import com.lagou.entity.COrder;
import com.lagou.repository.COrderRepository;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;

/**
 * @author mcl
 * @date 2021/10/4 14:13
 * @description
 */
@RestController
public class OrderController {

    @Autowired
    AmqpTemplate rabbitTemplate;
    @Autowired
    COrderRepository cOrderRepository;

    @GetMapping("/create")
    public String create() {

        Random random = new Random();
        int userId = random.nextInt(10);
        COrder order = new COrder();
        order.setUserId(userId);
        order.setStatus("Paying");
        order.setCreateTime(new Date());

        cOrderRepository.save(order);

        rabbitTemplate.convertAndSend("ex.go","go", order.getId());

        return String.valueOf(order.getId());
    }

    @GetMapping("/pay/{orderId}")
    public String pay(@PathVariable Long orderId) {
        Optional<COrder> byId = cOrderRepository.findById(orderId);
        if (byId.isPresent()) {
            COrder cOrder = byId.get();
            if (!"TimeOut".equals(cOrder.getStatus())) {
                cOrder.setStatus("Payed");
                cOrderRepository.saveAndFlush(cOrder);
                return "支付成功";
            } else {
                return "支付超时";
            }
        } else {
            return "订单不存在";
        }
    }
}
